<template>
  <MrCustom bg-color="bg-gradual-blue " is-back>
    <template #backText>
      返回
    </template>
  </MrCustom>

  <button class="avatar-wrapper round" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
    <image class="avatar round" :src="prefix+avatar"></image>
  </button>
  <view class="text-gray text-df text-center margin-bottom-lg">
    点击上传头像
  </view>
  <view class="shadow-warp bg-white margin padding radius-lg">
    <input required type="nickname" placeholder="请输入用户名" v-model="username"/>
  </view>
  <view class="shadow-warp bg-white margin padding radius-lg">
    <input placeholder="邀请码(可不填)" v-model="invitationCode"/>
  </view>
  <view class="flex flex-sub flex-direction margin-lg padding">
    <button class="cu-btn xxl round  bg-gradual-blue" @tap="onRegister">
      <text class="cuIcon-weixin">&nbsp;</text>
      <text class="text-xxl">微信注册</text>
    </button>
  </view>
</template>

<script setup lang="ts">

import {ref} from 'vue';
//@ts-ignore
import {imagePathPrefix, uploadFile} from '/settings'
import api from "@/api";
import MrCustom from "@/components/common/MrCustom.vue";

const url = uploadFile.url
const name = uploadFile.name
const prefix = imagePathPrefix

const avatar = ref('')
const username = ref('')
const invitationCode = ref('')

const onChooseavatar = (e: any) => {
  uni.uploadFile({
    url: url,
    filePath: e.detail.avatarUrl,
    name: name,
    success: (uploadFileRes) => {
      let tmp = JSON.parse(uploadFileRes.data).data
      avatar.value = tmp
      console.log(tmp)
    }
  });
}
const onRegister = () => {
  uni.login({
    provider: 'weixin',
    success: function (loginRes: any) {
      api.auth.register({
        code: loginRes.code,
        avatar: avatar.value,
        username: username.value,
        invitationCode: invitationCode.value
      }).then(response => {
        if (response && response.data.code === 0) {
          uni.redirectTo({
            url: '/pages/common/auth/login/login',
            success: function () {
              uni.showToast({
                icon: 'success',
                title: response.data.msg
              })
            }
          })
        } else {
          uni.showToast({
            icon: 'error',
            title: response.data.msg
          })
        }
      })
    }
  })

}
</script>

<style scoped>
.avatar-wrapper {
  padding: 0;
  width: 80px !important;
  margin-top: 40px;

}

.avatar {
  display: block;
  width: 80px;
  height: 80px;
}
</style>
